package com.qf.fmmall.service.impl;

import com.qf.fmmall.dao.OrderItemMapper;
import com.qf.fmmall.dao.OrdersMapper;
import com.qf.fmmall.dao.ProductSkuMapper;
import com.qf.fmmall.dao.ShoppingCartMapper;
import com.qf.fmmall.entity.*;
import com.qf.fmmall.pay.wxpay.WxpayUtils;
import com.qf.fmmall.service.OrderService;
import com.qf.fmmall.service.ShoppingCartService;
import com.qf.fmmall.vo.ResStatus;
import com.qf.fmmall.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private ProductSkuMapper productSkuMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo add(String cids, Orders order) {

        ResultVo vo = new ResultVo();

        //1.保存订单数据
        //1.1 校验库存
        ResultVo resultVo = shoppingCartService.listbycids(cids);
        List<ShoppingCartVo> shoppingCartVoList = (List<ShoppingCartVo>)resultVo.getData();

        StringBuilder stringBuilder = new StringBuilder();

        AtomicReference<Boolean> flag= new AtomicReference<>(true);//是否超库存 true代表没超库存
        shoppingCartVoList.forEach((shoppingCartVo -> {
            stringBuilder.append(shoppingCartVo.getProductName()+",");
            if (Integer.valueOf(shoppingCartVo.getCartNum())>shoppingCartVo.getStock()){
                flag.set(false);
            }
        }));

        if (flag.get()){ //没超库存

            //1.2 保存订单主表信息
            String orderIdStr = UUID.randomUUID().toString().replaceAll("-", "");
            order.setOrderId(orderIdStr);
            order.setUntitled(stringBuilder.toString());
            order.setStatus("1");
            order.setCreateTime(new Date());
            ordersMapper.insert(order);

            //1.3 保存订单明细表信息
            shoppingCartVoList.forEach((shoppingCartVo -> {
                OrderItem orderItem = new OrderItem();
                orderItem.setItemId(UUID.randomUUID().toString().replaceAll("-", ""));
                orderItem.setOrderId(orderIdStr);
                orderItem.setProductId(shoppingCartVo.getProductId());
                orderItem.setProductName(shoppingCartVo.getProductName());
                orderItem.setProductImg(shoppingCartVo.getProductImg());
                orderItem.setSkuId(shoppingCartVo.getSkuId());
                orderItem.setSkuName(shoppingCartVo.getSkuName());
                orderItem.setProductPrice(shoppingCartVo.getProductPrice());
                orderItem.setBuyCounts(Integer.valueOf(shoppingCartVo.getCartNum()));
                //计算总金额
                BigDecimal totalAmount = new BigDecimal(shoppingCartVo.getSellPrice() * Integer.valueOf(shoppingCartVo.getCartNum()));
                orderItem.setTotalAmount(totalAmount);
                orderItem.setBasketDate(new Date());
                orderItem.setBuyTime(new Date());
                orderItem.setIsComment(0);

                orderItemMapper.insert(orderItem);
            }));
            //1.4 减少商品套餐表里库存
                shoppingCartVoList.forEach(shoppingCartVo -> {
                    int newStockNum=shoppingCartVo.getStock()- Integer.valueOf(shoppingCartVo.getCartNum());

                    ProductSku productSku = new ProductSku();
                    productSku.setSkuId(shoppingCartVo.getSkuId());
                    productSku.setStock(newStockNum);
                    productSkuMapper.updateByPrimaryKeySelective(productSku);
                });
            //1.5 删除购物车表中对应的 cids的数据
            String[] cidsArr = cids.split(",");
            for (String cid: cidsArr) {
                shoppingCartMapper.deleteByPrimaryKey(cid);
            }
            //2.调用微信支付接口获取支付短链接字符串
            String payUrl = "";
            try {
                payUrl = WxpayUtils.getPayUrl(orderIdStr);
            } catch (Exception e) {
                e.printStackTrace();
            }

            HashMap<String, Object> map = new HashMap<>();
            map.put("orderId",orderIdStr);
            map.put("payUrl",payUrl);

            vo.setCode(ResStatus.OK);
            vo.setMsg("success");
            vo.setData(map);
        }else {  //超出库存
            vo.setCode(ResStatus.NO);
            vo.setMsg("购物车的商品数量超出了库存");
        }

        return vo;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public ResultVo queryOrderStatus(String orderId) {
        ResultVo vo = new ResultVo();

        try {
            String s = WxpayUtils.queryOrder(orderId);
            if (s!=null && s.equals("SUCCESS")){
                vo.setCode(ResStatus.OK);
                vo.setMsg("success");
                vo.setData(ResStatus.WX_PAY_OK); //成功的标识
            }else {
                vo.setCode(ResStatus.NO);
                vo.setMsg("该订单尚未支付成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return vo;
    }
}
